const { userModel } = require('../../model');
const number = require('../../services/learn_number');

module.exports = {
  /**
   * 根据机构代号org在userTeacher表中查询教师id
   * 根据教师id在user表中查询教师信息
   * */
  list: async (req, res) => {
    const result = await userModel.findByFilter([
      'id',
      'name',
      'account',
      'avatar',
      'createdAt'
    ], {
      org: req.decode.org,
      roles: 'teacher'
    }).catch(err => { console.log('errMessage: ' + err)});

    res.send({
      code: 20000,
      data: {
        items: result,
        total: result.length
      }
    })
  },
  create: function (req, res) {
    const { org } = req.decode;
    const { name, password, avatar } = req.body;

    number.setCustomerType('tea',function (account) {
      userModel.create({
        name: name,
        org: org,
        account: account,
        password: password,
        avatar: avatar,
        roles: 'teacher',
        updatedAt: Date.now(),
        createdAt: Date.now()
      })
        .then(() => {
          return res.send({
            code: 20000
          });
        }).catch(err => {
          console.log(err);
          return res.send({
            code: 10000
          });
        })
    });
  },
  update: function (req, res) {
    const { org } = req.decode;
    const { id } = req.params;
    const { name, avatar, password } = req.body;

    let attr = { name: name, avatar: avatar };
    if (password) attr['password'] = password;

    userModel.update(attr, { id: id, org: org })
      .then(function () {
        res.send({
          code: 20000
        })
      })
      .catch(function (err) {
        console.log(err);
        res.send({
          code: 10000
        })
      })
  },
  delete: function (req, res) {
    const { org } = req.decode;
    const { id } = req.params;

    userModel.delete({
      id: id,
      org: org,
      roles: 'teacher'
    }).then(function (result) {
      res.send({
        code: 20000
      })
    }).catch(function (err) {
      console.log(err)
      res.send({
        code: 10000
      })
    })
  }
};
